<template>
  <div class='container'>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!--  标题内容 -->
      <el-row>

        <el-col :span='4'
                class="addUsers">

          <el-button type='primary'
                     @click="dialogFormVisible=true"> 添加用户</el-button>

        </el-col>
      </el-row>

      <el-table :data="allRolesList"
                border
                stripe
                style="width: 100%">
        <!--  type = expand 表示展开 -->
        <el-table-column type="expand">
          <template slot-scope="props">

            <el-row v-for='(item1,index) in props.row.children'
                    :key="index"
                    class="rolesBox">
              <!-- {{props.row}} -->
              <!--  一级权限 -->
              <el-col :span='4'>

                <el-tag effect="dark"
                        closable
                        @close="deleteRoles(item1,props.row)"> {{item1.authName}}</el-tag>
                <i data-v-92add97e=""
                   class="el-icon-caret-right"></i>

              </el-col>

              <!--  二级 三级权限 -->

              <el-col :span='20'>
                <el-row v-for='(item2,index) in  item1.children'
                        :key="index">
                  <el-col :span='6'>
                    <el-tag effect="dark"
                            closable
                            type='success'
                            @close="deleteRoles(item2,props.row)"> {{item2.authName}}</el-tag>
                    <i data-v-92add97e=""
                       class="el-icon-caret-right"></i>

                  </el-col>
                  <el-col :span='18'>
                    <el-tag v-for='(item3,index) in  item2.children'
                            :key="index"
                            effect="dark"
                            closable
                            type='warning'
                            @close="deleteRoles(item3,props.row)"> {{item3.authName}}</el-tag>

                  </el-col>
                </el-row>

              </el-col>

            </el-row>

          </template>

        </el-table-column>

        <!-- //  "id": 30,
      //             "roleName": "主管",
      //             "roleDesc": "技术负责人", -->

        <el-table-column label="#"
                         width="150"
                         align='center'>
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="角色名称"
                         align='center'>
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.roleName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="角色描述"
                         align='center'>
          <template slot-scope="scope">

            <span style="margin-left: 10px">{{ scope.row.roleDesc }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作"
                         align='center'>
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>

            <el-button size="mini"
                       type="warning"
                       @click="changeGrantRole(scope.$index, scope.row)">角色授权</el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-card>

    <!-- 角色授权弹框  :before-close="handleClose" -->
    <el-dialog title="授权角色"
               :visible.sync="dialogVisible"
               width="30%">

      <el-tree :data="allRolesTree"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-expanded-keys="expandedKeys"
               :default-checked-keys="checkedKeys"
               :props="defaultProps"
               ref="tree"
               @check-change='changeStatus'>
      </el-tree>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="sureGrantRolesBtn">确 定</el-button>
        <!-- dialogVisible = false -->
      </span>
    </el-dialog>

  </div>
</template>

<script>

import { getRightsTree, getRightsList, getRolesList, getSureRolesRights, deleteRolesRightsId } from '../../api';
export default {
  name: '',
  data () {
    return {
      allRolesList: [],
      allRolesTree: [],
      dialogVisible: false,

      defaultProps: {
        children: 'children',
        label: 'authName'
      },

      expandedKeys: [],
      checkedKeys: [],
      allCheckedId: [],
      roleId: '' // 角色id


    }


  },
  methods: {
    // 关闭弹框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },

    // 打开 弹框授权 
    changeGrantRole (index, row) {
      this.checkedKeys = []; // 初始化回到最初的状态  bug 修复 

      // alert('打开')
      // 1 打开弹框 
      // 2 填充所有的授权tree 展示     默认全部展开    
      // 3 针对已经存在的授权角色  需要 选中
      this.dialogVisible = true
      //   this.getExpandedId(this.allRolesTree, this.expandedKeys)

      console.log(row);
      this.roleId = row.id


      this.getCheckedId(row.children, this.checkedKeys)
      this.initGetRightsTree()

    },

    // 获取全选以及半选的id
    changeStatus (a, b, c) {



      let CheckedKeys = this.$refs.tree.getCheckedKeys()
      console.log('全选', CheckedKeys);

      let halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()

      console.log('半选', halfCheckedKeys);

      this.allCheckedId = [...CheckedKeys, ...halfCheckedKeys]


    },

    // 真正的确定授权角色
    async sureGrantRolesBtn () {
      // 1 组装 我们 params 参数  要求字符串 
      let rids = this.allCheckedId.join(',') //  权限 ID 列表（字符串)
      //   this.roleId  角色id

      //   2 发送axios      失败 给出提示 
      //  3  成功了  给出提示   关闭弹框   重新加载更新后的数据
      let params = { rids: rids, roleId: this.roleId }
      let { data, meta: { status, msg } } = await getSureRolesRights(params)
      //   console.log(data);
      if (status != 200) return this.$message.info(msg)
      this.$message.success(msg)
      this.dialogVisible = false;
      //   ???? 重新加载更新后的数据
      this.initGetRolesList()



    },



    // 获取选中的id  
    getCheckedId (treeNode, treeArrId) {


      treeNode.forEach(item => {
        //表示最后一层
        if (!item.children) {
          return treeArrId.push(item.id)
        }
        // 能够走下面的代码 一定有children 
        return this.getCheckedId(item.children, treeArrId)
      })

      console.log(treeArrId);


    },

    //  关闭权限角色 tag 事件  
    async deleteRoles (currentItem, currentRow) {
      console.log(currentRow.id);
      console.log(currentItem);
      console.log('----------');
      let params = {
        roleId: currentRow.id,
        rightId: currentItem.id
      }
      let { data, meta: { msg, status } } = await deleteRolesRightsId(params)
      // "msg": "取消权限成功",
      //         "status": 200
      if (status != 200) return this.$message.info('删除角色权限失败')
      this.$message.success('成功')
      console.log(data);
      // this.initGetRolesList()
      currentRow.children = data

      // this.allRolesTree = data





    },

    initGetRolesList () {
      getRolesList().then(res => {
        this.allRolesList = res.data
      })
    },

    initGetRightsTree () {
      getRightsTree().then(res => {
        console.log(res);
        this.allRolesTree = res.data

      })

    }

  },


  mounted () {
    // 获取角色列表 
    this.initGetRolesList()
    // 获取角色授权tree
    this.initGetRightsTree()









  }
}
</script>

<style scoped lang='less'>
.addUsers {
  text-align: center;
}

.el-table {
  margin-top: 20px;
  text-align: center;
}

.el-pagination {
  margin: 10px 200px;
}

.firstRoles > .el-col {
  margin: 5px 0;
}

.el-row .el-col {
  padding: 5px;
}

.el-tag {
  margin: 5px;
}
</style>